// pages/menu/data-magic/order-statistics/order-statistics.js
var wxCharts = require('../../../../utils/wxcharts.js')
var daylineChart = null;
var yuelineChart = null; 
var verify = require('../../../../utils/verify-token.js')
const moment = require('../../../../utils/moment.min')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    queryBy:"day",
    startTime:"",
    endTime:"",
    queryDayType: "td",
    filterType: "deviceFilter",
    filterValue: "ALL",
    mid: 0.021,
    lid: 0.03,
    selectDate:true,
    selectMonth:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options = ", options.filterValue ==undefined)
    if (options.filterValue != undefined){
      this.setData({
        filterValue: options.filterValue
      })
    }
    if (options.filterType != undefined) {
      this.setData({
        filterType: options.filterType
      })
    }
    if (options.values != undefined) {
      this.setData({
        values: options.values
      })
    }
    this.setData({
      sh: app.globalData.screenHeight,
      sw: app.globalData.screenWidth
    })

    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取年份  
    var Y = date.getFullYear();
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var td = Y + '-' + M + '-' + D
    // console.log("当前时间：" + td);
    this.setData({
      td:td,
      startTime: td,
      endTime: td
    })
  },

  // 获取订单统计
  getOrderData(){
    var queryBy = this.data.queryBy
    var startTime = this.data.startTime
    var endTime = this.data.endTime
    var queryDayType = this.data.queryDayType
    var filterType = this.data.filterType
    var filterValue = this.data.filterValue
    if (filterType == "deviceFilter" && filterValue!="ALL"){
      filterValue = this.data.values
    }
    if (filterType == "locationFilter" && filterValue!="ALL"){
      filterValue = this.data.values
    }
    if (filterType == "companyFilter" && filterValue != "ALL") {
      filterValue = this.data.values
    }
    // console.log("queryBy = ", queryBy)
    // console.log("startTime = ", startTime)
    // console.log("endTime = ", endTime)
    // console.log("queryDayType = ", queryDayType)
    // console.log("filterType = ", filterType)
    // console.log("filterValue = ", filterValue)

    var token = app.globalData.token
    var baseUrl = app.globalData.baseUrl
    var that = this

    wx.request({
      url: baseUrl + 'orderQuery',
      data:{
        queryBy: queryBy,
        startTime: startTime,
        endTime: endTime,
        queryDayType: queryDayType,
        filterType: filterType,
        filterValue: filterValue,
      },
      header: {
        'AUTHORIZATION': token
      },
      success: function (res) {
        if (res.data.code == 60006) {
          verify.clearAll()
        } else if (res.data.code == 200) {
          console.log("orderData = ", res.data.data)
          var orderData = res.data.data
          that.setData({
            orderData: orderData
          })
          that.getMothElectro();
        } else {
          wx.showModal({
            title: '操作失败',
            content: res.data.message,
          })
        }
      }
    })
  },

  // 获取用电统计图
  getMothElectro: function () {
    var windowWidth = this.data.sw;
    var orderData = this.data.orderData
    var countCategories = orderData.orderCountTrendVo.xData
    var countData = orderData.orderCountTrendVo.yData
    var moneyCategoriesy = orderData.orderMoneyTrendVo.xData
    var moneyData = orderData.orderMoneyTrendVo.yData
    var countMax = countData[0]
    var moneyMax = moneyData[0]
    for (var i = 1; i < countData.length;i++){
      if (countMax < countData[i]){
        countMax = countData[i]
      }
    }
    for (i = 1; i < moneyData.length; i++) {
      if (moneyMax < moneyData[i]) {
        moneyMax = moneyData[i]
      }
    }

    try {
      var res = wx.getSystemInfoSync();
      windowWidth = windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    yuelineChart = new wxCharts({ //当月用电折线图配置
      canvasId: 'yueEle',
      type: 'line',
      categories: countCategories, //categories X轴
      animation: true,
      // background: '#f5f5f5',
      series: [{
        name: '订单数量',
        data: countData,
        format: function (val, name) {
          return val.toFixed(2) + 'kWh';
        }
      }
      // , {
      //   name: '电池供电量',
      //   data: [0, 6, 2, 2, 7, 6, 2, 5, 8, 1, 8, 4, 0, 9, 7, 2, 5, 2, 8, 2, 5, 2, 9, 4, 4, 9, 8, 5, 5, 5, 6],
      //   format: function (val, name) {
      //     return val.toFixed(2) + 'kWh';
      //   }
      // },
      // {
      //   name: '光伏供电量',
      //   data: [6, 4, 9, 7, 1, 4, 5, 1, 1, 8, 8, 6, 6, 2, 2, 2, 0, 5, 5, 8, 8, 8, 8, 9, 0, 4, 6, 9, 2, 1, 6],
      //   format: function (val, name) {
      //     return val.toFixed(2) + 'kWh';
      //   }
      // },
      // {
      //   name: '市电供电量',
      //   data: [0, 4, 3, 3, 1, 7, 7, 7, 9, 9, 3, 3, 0, 0, 5, 6, 0, 4, 1, 2, 0, 1, 3, 9, 2, 5, 1, 8, 3, 4, 2],
      //   format: function (val, name) {
      //     return val.toFixed(2) + 'kWh';
      //   }
      // }
      ],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '订单数量（个）',
        format: function (val) {
          return val.toFixed(2);
        },
        max: countMax*1.2,
        min: 0
      },
      width: windowWidth,
      height: 200,
      dataLabel: false,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });


    yuelineChart = new wxCharts({ //当月用电折线图配置
      canvasId: 'yueEle1',
      type: 'line',
      categories: moneyCategoriesy, //categories X轴
      animation: true,
      // background: '#f5f5f5',
      series: [{
        name: '订单总额',
        //data: yuesimulationData.data,
        data: moneyData,
        format: function (val, name) {
          return val.toFixed(2) + 'kWh';
        }
      }
      ],
      xAxis: {
        disableGrid: true
      },
      yAxis: {
        title: '订单总额（元）',
        format: function (val) {
          return val.toFixed(2);
        },
        max: moneyMax*1.2,
        min: 0
      },
      width: windowWidth,
      height: 200,
      dataLabel: false,
      dataPointShape: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },


  yueTouchHandler: function (e) { //当月用电触摸显示
    console.log(daylineChart.getCurrentDataIndex(e));
    yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
      background: '#7cb5ec',
      format: function (item, category) {
        return category + '日 ' + item.name + ':' + item.data
      }
    });
  },

  // 看看是按什么filterType统计
  filterType1(res){
    var filterType = res.currentTarget.dataset.filtertype;
    this.setData({
      filterType: filterType,
      filterValue:"ALL"
    })
    this.getOrderData()
  },

  // 修改起始日期
  changeStartDate: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      startTime: e.detail.value,
      queryDayType:""
    })
    this.getOrderData();
  },
  // 修改结束日期
  changeEndDate: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endTime: e.detail.value,
      queryDayType:""
    })
    this.getOrderData();
  },

  // 看看是按什么queryDayType统计
  queryDayType1(res) {
    var queryDayType = res.currentTarget.dataset.querydaytype;
    let ttoday = new Date();  
    let yestd = new Date();
    yestd.setDate(ttoday.getDate() - 1); 
    let dy7 =  new Date();
    dy7.setDate(ttoday.getDate() - 7); 
    let dy30 =  new Date();
    dy30.setDate(ttoday.getDate() - 30); 
    // console.log("queryDayType = ", queryDayType)
    let startTime = '',endTime='';    
    switch(queryDayType){
      case 'td':
        startTime = moment(ttoday).format("YYYY-MM-DD");
        endTime = moment(ttoday).format("YYYY-MM-DD");
        break;
      case 'yd':
        endTime = moment(ttoday).format("YYYY-MM-DD");
        startTime = moment(yestd).format("YYYY-MM-DD");
        break;
      case '7d':
        endTime = moment(ttoday).format("YYYY-MM-DD");
        startTime = moment(dy7).format("YYYY-MM-DD");
        break;
      case '30d':
        endTime = moment(ttoday).format("YYYY-MM-DD");
        startTime = moment(dy30).format("YYYY-MM-DD");
        break;
      default:
        startTime = moment(ttoday).format("YYYY-MM-DD");
        endTime = moment(ttoday).format("YYYY-MM-DD");
        break;
    }
    this.setData({
      queryDayType: queryDayType,
      startTime:startTime,
      endTime:endTime
    })
    this.getOrderData()
  },

  search(res){
    var filterType = this.data.filterType
    wx.redirectTo({
      url: 'search/search?filterType=' + filterType,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    this.getOrderData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})